Chapter 7 Visualizing Spatial Data
7.1 Lesson Goals
- Explore a basics of several mapping libraries in R
- Construct a couple example visualizations with spatial data in R
R is fantastic for making publication quality static maps, and for generating repetitive graphics through scripts; we’ve already seen how to make simple maps using base plotting,ggplot, and tmap. There are also a number of packages in R that link R code to plotting libraries developed in Javascript (or other languages) for interactive plotting and web integration.
7.2 Chorpleths with tmap
Load tidycensus - you’ll need to set your Census API key. A key can be obtained from here. Here we make a choropleth map of median household income in Travis county in Texas.
library(sf)## Warning: package 'sf' was built under R version 4.0.5
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(tidycensus)## Warning: package 'tidycensus' was built under R version 4.0.5
# census_api_key("YOUR API KEY GOES HERE")library(tidycensus)
library(tmap)
options(tigris_use_cache = FALSE)
austin_tracts <- get_acs(state = 'TX', county = 'Travis', geography = "tract",
variables = "B19013_001", geometry = TRUE)
tm_shape(austin_tracts) + tm_polygons("estimate")
7.3 leaflet
Leaflet is an extremely popular open-source javascript library for interactive web mapping, and the leaflet R package allows R users to create Leaflet maps from R. Leaflet can plot sf or sp objects, or x / y coordinates, and can plot points, lines or polygons. There are a number of base layers you can choose from. It’s worth spending some time exploring the excellent Leaflet for R site.
Here we make the simplest of leaflet maps:
library(leaflet)
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=-123.26720, lat=44.5810, popup="Here's my house")
m # Print the map7.4 mapview
Mapview is a package designed for quick and easy interactive visualizations of spatial data - it makes use of leaflet but simplifies mapping functions compared to the leaflet package.
It’s easy to layer features with mapview - you can supply a list of objects to mapview or use + syntax as with ggplot.
library(Rspatialworkshop)
library(mapview)
data(bike_paths)
data(parks)
mapview(bike_paths) + parks